// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.core.utils;

import static org.dengues.core.runprocess.JavaProcessorUtil.CUSTOMERAPI_PKG;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.util.Formatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.dengues.commons.utils.FileUtils;
import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.ExceptionOperation;
import org.dengues.core.module.EMFModule;
import org.dengues.core.module.IModuleScriptSynchronizer;
import org.dengues.core.resource.WarehouseResourceFactory;
import org.dengues.core.runprocess.JavaProcessorUtil;
import org.dengues.core.warehouse.ENodeCategoryName;
import org.dengues.designer.core.launch.JavaETLProcessor;
import org.dengues.model.component.IMPORTType;
import org.dengues.model.warehouse.ScriptsStorage;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.util.EList;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-4-28 qiang.zhang $
 * 
 */
public class ModuleScriptSynchronizer implements IModuleScriptSynchronizer {

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.module.IModuleScriptSynchronizer#getJavaFile(org.dengues.model.warehouse.ScriptsStorage)
     */
    public IFile getJavaFile(ScriptsStorage storage) {
        IProject project = JavaETLProcessor.getProject();
        IFolder folder = project.getFolder(JavaProcessorUtil.JAVA_PROJ_SRC).getFolder(JavaProcessorUtil.JAVA_DENGUES_PKG)
                .getFolder(JavaProcessorUtil.CUSTOMERAPI_PKG);
        return folder.getFile(storage.getName() + JavaProcessorUtil.JAVA_EXTENSION);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.module.IModuleScriptSynchronizer#synchronizeScript(org.dengues.model.warehouse.ScriptsStorage)
     */
    public String synchronizeScript(ScriptsStorage storage, boolean create, String oldName) {
        String content = storage.getContent();
        try {
            IProject project = JavaETLProcessor.getProject();
            File prjFile = project.getLocation().toFile();
            File srcFile = new File(prjFile, JavaProcessorUtil.JAVA_PROJ_SRC);
            prjFile = new File(srcFile, JavaProcessorUtil.JAVA_DENGUES_PKG);
            File dirFile = new File(prjFile, JavaProcessorUtil.CUSTOMERAPI_PKG);
            srcFile = new File(dirFile, storage.getName() + JavaProcessorUtil.JAVA_EXTENSION);
            String contentStr = "";
            if (create) {
                File denguesApiPkg = JavaETLProcessor.getDenguesApiPkg();
                File file = new File(denguesApiPkg, TEMPLATE + JavaProcessorUtil.JAVA_EXTENSION);
                if (file.exists()) {
                    FileUtils.copy(file, srcFile);
                    contentStr = FileUtils.getStringFromStream(new FileInputStream(srcFile));
                    contentStr = contentStr.replaceAll(TEMPLATE, storage.getName());
                    contentStr = contentStr.replaceAll("package dengues;", "package " + JavaProcessorUtil.JAVA_DENGUES_PKG + "."
                            + CUSTOMERAPI_PKG + ";");
                    content = contentStr;
                }
            } else {
                new File(dirFile, oldName + JavaProcessorUtil.JAVA_EXTENSION).delete();
                contentStr = new String(content);
                contentStr = contentStr.replaceAll("public class " + oldName, "public class " + storage.getName());
            }
            FileWriter writer = new FileWriter(srcFile);
            Formatter formatter = new Formatter(writer);
            writer.write(contentStr, 0, contentStr.length());
            formatter.flush();
            // writer.flush();
            writer.close();
            project.refreshLocal(IResource.DEPTH_INFINITE, null);
        } catch (Exception e) {
            ExceptionOperation.operate(e);
        }
        return content;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.module.IModuleScriptSynchronizer#getScriptAllModules()
     */
    public Set<EMFModule> getScriptAllModules() {
        Set<EMFModule> set = new HashSet<EMFModule>();
        List<Object> allObj = WarehouseResourceFactory.getAllObjectsFromEMF(ENodeCategoryName.SCRIPTS);
        try {
            for (Object object : allObj) {
                ScriptsStorage storage = (ScriptsStorage) object;
                EList<IMPORTType> imports = storage.getImports();
                for (IMPORTType type : imports) {
                    EMFModule module = new EMFModule();
                    IPath append = DenguesCorePlugin.getCustomModulePath().append(type.getMODULE());
                    module.setName(type.getNAME());
                    module.setLibJar(type.getMODULE());
                    module.setUrl(new File(append.toPortableString()).toURL());
                    set.add(module);
                }
            }
        } catch (MalformedURLException e) {
            ExceptionOperation.operate(e);
        }
        return set;
    }
}
